# -*- coding: utf-8 -*-
from config import *
import requests
import re
import os

class Spider( object ):
    def __init__(self):
        self.filename = "人民日报"
    # 访问抖音视频页面
    def RequestIndex(self,data =None ):

        url = ( domain["video_url"].format( data["aweme_id"]) )

        r = requests.get( url = url ,headers=general_header)


        if r.status_code == 200:

            html = r.text

            video_url = re.search(r'playAddr: "(.*)"', html).groups(1)[0]

            if len( video_url ) == 0:

                return

            print( video_url )

            result = {
                "desc":data["desc"],
                "stream":self.RequestVideo( video_url ),
                "download_url":video_url
            }

            self.Downloader( result )



    # 访问视频详情
    def RequestVideo(self,video_url):

        r = requests.get( url = video_url,headers=video_header )

        if r.status_code == 200:

            return r.content

    # 进行下载操作
    def Downloader(self,data=None):

        if not os.path.exists( self.filename ):

            os.mkdir( self.filename )

        with open("./{0}/{1}.mp4".format( self.filename,data["desc"]),mode="ab+") as f:

            f.write( data["stream"] )

        print("下载完成:%s"%(data["download_url"]) )


if __name__ == '__main__':
    s = Spider()
    s.RequestIndex()
